<script lang="ts">
  import { onMount } from 'svelte';

  export let notices: string[] = [];
  let noticeList: string[] = [];
  let scrollContainer: HTMLDivElement;
  let scrollAmount = 1; // 每次滚动的像素数
  let intervalId: number;

  $: {
    if (notices.length > 0) {
      noticeList = [...notices, ...notices]; // 复制一份以实现无缝滚动
    }
  }

  function startScrolling() {
    intervalId = setInterval(() => {
      if (scrollContainer) {
        scrollContainer.scrollLeft += scrollAmount;
        // 如果滚动到一半，重置到开始
        if (scrollContainer.scrollLeft >= scrollContainer.scrollWidth / 2) {
          scrollContainer.style.transition = 'none'; // 取消过渡效果
          scrollContainer.scrollLeft = 0;
          // 强制重绘以应用无过渡的滚动
          scrollContainer.offsetHeight; // 触发重绘
          scrollContainer.style.transition = 'scroll-left 0.1s linear'; // 恢复过渡效果
        }
      }
    }, 60); // 调整这个值以改变滚动速度
  }

  function stopScrolling() {
    clearInterval(intervalId);
  }

  onMount(() => {
    startScrolling();
    return () => stopScrolling();
  });
</script>

<div class="h-8 bg-[#172238] text-white flex items-center overflow-hidden">
  <div class="flex-shrink-0 px-3 relative z-10">
    <img src="/dp/xiaoxi@2x.png" alt="通知" class="w-5 h-5" />
  </div>
  <div class="relative flex-1 overflow-hidden" bind:this={scrollContainer} style="transition: scroll-left 0.1s linear;">
    <div class="whitespace-nowrap flex items-center h-full">
      {#each noticeList as notice}
        <span class="inline-block px-4">
          {@html notice}
        </span>
      {/each}
    </div>
  </div>
</div>

<style>
  /* .notice-bar {
    animation: scroll-left 15s linear infinite;
    animation-delay: 1s;
  } */
</style>